/*
 * Set.java
 *
 * Created on 27 novembre 2007, 14:02
 */
package com.reimscopie.console ;


/**
 * This command access local variables.
 */
public class Set extends Command {
  
  /**
   * Create a new <code>Set</code> instance.
   */
  public Set() {
    
  }
  
  
  /**
   * Return the name of this command. The name is the first word in the shell
   * command line.
   *
   * @return The command name.
   */
  @Override
  public String getName() {
    return "set" ;
  }
  
  
  /**
   * Return a short help message about this command.
   *
   * @return The command help.
   */
  @Override
  public String getHelp() {
    return "Display local variables" ;
  }
  
  
  /**
   * Return the command usage. This string must give all command options with
   * a description for each option.
   *
   * @return The command usage.
   */
  @Override
  public String getUsage() {
    return "set [name [value]]" ;
  }
  
  
  /**
   * Execute this command.
   * 
   * @param args The arguments given in the command line.
   * @param output The command output.
   */
  @Override
  public void execute(String[] args,ConsoleOutput output) {
    
    String name  = getParameter(0,args) ;
    String value = getParameter(1,args) ;
    
    // print all variables
    if (name == null)
      printAll(output) ;
    
    // print a specific value
    else if (value == null)
      printValue(name,output) ;
    
    // set a new value
    else
      setValue(name,value,output) ;
  }
  
  
  /**
   * Print all variable.
   *
   * @param output The console output.
   */
  private void printAll(ConsoleOutput output) {
    
    String[] names = getVariableNames() ;
    
    if (names == null  ||  names.length == 0) {
      output.print("No varaible",true) ;
    }
    
    
    for (String name : names) {
      Object value = getVariable(name) ;
      output.print(name) ;
      output.print(": ") ;
      output.print(value.toString()) ;
      output.println() ;
    }
    
  }
  
  
  /**
   * Print the specified variable.
   *
   * @param name The variable name.
   * @param output The console output.
   */
  private void printValue(String name,ConsoleOutput output) {
    
    Object value = getVariable(name) ;
    
    if (value == null) {
      output.print("No such variable",true) ;
      return ;
    }
    
    
    Class clazz = value.getClass() ;
    
    output.print(value.toString(),true) ;
    output.print("Class: ") ;
    output.print(clazz.getName(),true) ;
  }
  
  
  /**
   * Set a variable value.
   *
   * @param name The variable name.
   * @param value The variable value.
   * @param output The console output.
   */
  private void setValue(String name,String value,ConsoleOutput output) {
    
    setVariable(name,value) ;
    output.print("Done",true) ;
  }
  
}
